package com.ruoyi.web.controller.wxauthor;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.AuthUtil;
import com.ruoyi.web.controller.config.WxConfig;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: TODO
 * @Author ONESTAR
 * @Date: 2021/7/10 17:15
 * @Version 1.0
 */
@Controller
@RequestMapping("/callBack")
public class CallBackController extends HttpServlet {
    // Step2 通过code换取网页授权access_token(暂时未用到)以及openid
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public void getUserInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String code = req.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + WxConfig.APPID +
                "&secret=" + WxConfig.APP_SECRET +
                "&code=" + code +
                "&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        String openid = jsonObject.getString("openid");

        String token = jsonObject.getString("access_token");
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" + token +
                "&openid=" + openid  +
                "&lang=zh_CN";
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        String headimgurl = userInfo.getString("headimgurl");
        resp.sendRedirect(WxConfig.CLIENT_BASE_URL+"?openid="+openid+"&headimgurl="+headimgurl);
        return;
    }



}
